package com.tim.helper.file;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author Adminis
 * @date 2020年10月13日
 * DESC: Files.walkFileTree替换为thymleaf语法
 */
@Slf4j
public class HandleStaticHtml {
	String dir = "C:/Users/Adminis/Desktop/start/html/";
	//替换
	Map<String, String> map = new HashMap<>();
	{
		map.put("src=\"../../", "th:src=\"@{/");
		map.put(".js\"", ".js}\"");
		map.put("href=\"../../", "th:href=\"@{/");
		map.put(".css\"", ".css}\"");
		map.put(".png\"", ".png}\"");
		map.put(".jpg\"", ".jpg}\"");
	}
	
	@Test
	public void walkFileTree() throws IOException {
		Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
				String fileName = path.getFileName().toString();
				System.out.println(fileName);
				List<String> lines = doReplace(fileName);
				Files.write(path, lines);
				return FileVisitResult.CONTINUE;
			}
			
		});
	}
	@Test
	public void replaceOne() throws IOException {
		String fileName = "lz_repeatedly_tips.html";
		List<String> lines = doReplace(fileName);
//		doReplace(fileName).forEach(System.out::println);
		Files.write(Paths.get(dir, fileName), lines);
	}
	private List<String> doReplace(String fileName) throws IOException {
		List<String> contents = Files.readAllLines(Paths.get(dir, fileName));
		List<String> result = new ArrayList<>();
		for (int i = 0; i < contents.size(); i++) {
			String item = contents.get(i);
			for(Entry<String, String> entry : map.entrySet()) {
				item = item.replace(entry.getKey(), entry.getValue());
			}
			result.add(item);
		}
		return result;
	}
}
